import { createApp, App } from 'vue';

interface RenderComponentOptions {
  el: Element | null;
  component: any;
  props?: Record<string, any>;
  appContext?: Record<string, any>;
}

export default function renderComponent({
  el,
  component,
  props,
  appContext,
}: RenderComponentOptions): () => void {
  // Check if the provided 'el' is a valid DOM element
  if (!el || !(el instanceof Element)) {
    console.error('Invalid element provided. Unable to mount component.');
    return () => {}; // Return an empty function or add your desired logic
  }

  let app: App | undefined = createApp(component, props);
  Object.assign(app?._context, appContext); // must use Object.assign on _context
  app?.mount(el);

  return () => {
    // Check if the app is mounted before unmounting
    if (app && app._container && app._container.parentNode) {
      app.unmount();
    }
    app = undefined;
  };
}
